/*
 *   Copyright©2021 JoyCastle.
 *   All Rights Reserved.
 *   
 *   FileName:     DataCommonSave.cs
 *   Author:       VirgilWei
 *   CreateTime:   2021/08/11 14:26:27
 *   UnityVersion: 2020.3.13f1c1
 *   Version:      2.0.7
 *   Description:
 *   
 */

using System.Collections;
using System.Collections.Generic;
using SevenPieceGame.Archive;
using UnityEngine;

public class DataSaveHelper : Singleton<DataSaveHelper>, IArchive
{
    public Dictionary<string, string> _dic = new Dictionary<string, string>();

    public string SaveKey { get { return "DataCommonSaveKey"; } }

    public bool IsNeedSave { get; set; }

    public object SaveContent { get { return _dic; } }

    private bool _isInit = false;

    /// <summary>
    /// 初始化
    /// </summary>
    private void Init() 
    {
        if (!_isInit) 
        {
            _dic = ArchiveService.ReadArchive<Dictionary<string, string>>(SaveKey);
            _isInit = true;
        }
    }

    /// <summary>
    /// 添加数据
    /// </summary>
    /// <param name="key"></param>
    /// <param name="o"></param>
    public void Add(string key, string o)
    {
        Init();
        if (_dic.ContainsKey(key))
        {
            _dic[key] = o;
        }
        else
        {
            _dic.Add(key, o);
        }
        IsNeedSave = true;
        ArchiveService.SaveArchives(this);
    }

    /// <summary>
    /// 获取值类型
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public string Get(string key)
    {
        Init();
        if (_dic.ContainsKey(key))
        {
            return _dic[key];
        }
        return null;
    }

    /// <summary>
    /// 清理key
    /// </summary>
    /// <param name="key"></param>
    public void CleanKey(string key)
    {
        Init();
        if (_dic.ContainsKey(key))
        {
            _dic.Remove(key);
            IsNeedSave = true;
            ArchiveService.SaveArchives(this);
        }
    }

    /// <summary>
    /// 是否拥有当前key
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public bool Own(string key)
    {
        Init();
        return _dic.ContainsKey(key);
    }
}